package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-mgmt-sys/cache"
	"order-mgmt-sys/model"
	"time"
)

func Peopleadd(c *gin.Context) {
	name := c.PostForm("name")
	if name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	data := model.People{
		Name: name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func Orderadd(c *gin.Context) {
	name := c.PostForm("name")
	if name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	data := model.Order{
		Name: name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Orderlist(c *gin.Context) {
	var order []model.Order
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
func OrderlistD(c *gin.Context) {
	id := c.Query("id")
	var order []*model.Order
	redis_key := "l_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&order)
		jsonData, _ := json.Marshal(&order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
